package com.lesson60.action;

import com.lesson60.sshdemo.PersistenceLayer;
import com.lesson60.sshdemo.User;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	
	public String username, password;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public PersistenceLayer mPersistenceLayer;
	
	public PersistenceLayer getmPersistenceLayer() {
		return mPersistenceLayer;
	}
	public void setmPersistenceLayer(PersistenceLayer mPersistenceLayer) {
		this.mPersistenceLayer = mPersistenceLayer;
	}
	/**
	 * @return
	 */
	public String execute() {
		if(mPersistenceLayer == null){
			System.out.println("mPersistenceLayer doesn't init.");
		}else{
			System.out.println("mPersistenceLayer inited.");
		}
		deleteUser();
		addUser();
		findUser();
		if(getPassword() != null && getUsername() != null){
			return SUCCESS;
		}else{
			return ERROR;
		}
	}
	
	private void addUser(){
		/*create user*/
		Integer id = new Integer(1);
		User user = new User();
		user.setId(id);
		user.setUsername(username);
		user.setPassword(password);
		user.setFirstName("qingcai");
		user.setLastName("zhang");
		user.setPassword("root");
		user.setDateCreated(Long.valueOf(System.currentTimeMillis()));
		
		/*
		 * add user to db.
		 */
		getmPersistenceLayer().addUser(user);
	}
	
	private void findUser(){
		User userLoadedFromDB = mPersistenceLayer.findUserById(1); 
        System.out.println("User Loaded from DB [username=" 
                + userLoadedFromDB.getUsername() + ", password=" 
                + userLoadedFromDB.getPassword() + ", firstName=" 
                + userLoadedFromDB.getFirstName() + ", lastName=" 
                + userLoadedFromDB.getLastName() + "]"); 
	}
	
	private void deleteUser(){
		
	}
	
}